/// 积分套餐数据模型
class PointsPackage {
  final int packageId;
  final String packageName;
  final int pointsAmount;
  final double price;
  final double originalPrice;
  final double discountAmount;
  final int discountPercentage;
  final String packageDescription;
  final bool isPopular;
  final bool isActive;
  final int sortOrder;
  final String iconUrl;

  PointsPackage({
    required this.packageId,
    required this.packageName,
    required this.pointsAmount,
    required this.price,
    required this.originalPrice,
    required this.discountAmount,
    required this.discountPercentage,
    required this.packageDescription,
    required this.isPopular,
    required this.isActive,
    required this.sortOrder,
    required this.iconUrl,
  });

  /// 从JSON创建PointsPackage对象
  factory PointsPackage.fromJson(Map<String, dynamic> json) {
    // 处理布尔值字段（API返回0/1）
    bool parseIntToBool(dynamic value) {
      if (value is bool) return value;
      if (value is int) return value == 1;
      if (value is String) return value == '1' || value.toLowerCase() == 'true';
      return false;
    }

    return PointsPackage(
      packageId: json['package_id'] ?? 0,
      packageName: json['package_name'] ?? '',
      pointsAmount: json['points_amount'] ?? 0,
      price: (json['price'] ?? 0.0).toDouble(),
      originalPrice: (json['original_price'] ?? 0.0).toDouble(),
      discountAmount: (json['discount'] ?? 0.0).toDouble(),
      discountPercentage: json['discount_percentage'] ?? 0,
      packageDescription: json['package_description'] ?? '',
      isPopular: parseIntToBool(json['is_popular']),
      isActive: parseIntToBool(json['is_active']),
      sortOrder: json['sort_order'] ?? 0,
      iconUrl: json['icon_url'] ?? '',
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'package_id': packageId,
      'package_name': packageName,
      'points_amount': pointsAmount,
      'price': price,
      'original_price': originalPrice,
      'discount': discountAmount,
      'discount_percentage': discountPercentage,
      'package_description': packageDescription,
      'is_popular': isPopular ? 1 : 0,
      'is_active': isActive ? 1 : 0,
      'sort_order': sortOrder,
      'icon_url': iconUrl,
    };
  }

  /// 获取格式化的积分显示
  String get formattedPoints => '${pointsAmount}积分';

  /// 获取格式化的价格显示
  String get formattedPrice => '¥${price.toStringAsFixed(1)}';

  /// 获取格式化的原价显示
  String get formattedOriginalPrice => '¥${originalPrice.toStringAsFixed(1)}';

  /// 是否有折扣
  bool get hasDiscount => discountPercentage > 0;

  /// 获取折扣百分比显示
  String get discountPercent => '${discountPercentage}%';

  /// 获取折扣金额显示
  String get formattedDiscountAmount => '¥${discountAmount.toStringAsFixed(1)}';

  @override
  String toString() {
    return 'PointsPackage{packageId: $packageId, packageName: $packageName, pointsAmount: $pointsAmount, price: $price, discountPercentage: $discountPercentage}';
  }
}
